/**
 *@File ExeUploadInfoDatabase.cpp
 *
 *@Author: Bob
 *
 *@Create Time: 2017-4-18 11:45:14
 *
 *@Last Modify: Bob
 *
 *@Last Modify Time: 2017-4-18 11:45:14
 *
 *@Description:
 *   
 *
 */

#include "SqliteWrapper.h"
#include "ExeUploadInfoDatabase.h"


ExeUploadInfoDatabase::ExeUploadInfoDatabase()
{
}


ExeUploadInfoDatabase::~ExeUploadInfoDatabase()
{
	ReleaseHandle();
}


ExeUploadInfoDatabase* ExeUploadInfoDatabase::GetInstance()
{
	static ExeUploadInfoDatabase exeUploadInfoDatabase;
	return &exeUploadInfoDatabase;
}


bool ExeUploadInfoDatabase::Initialize(std::string& strDBPath)
{
	if (m_pSqliteWrapper == NULL)
	{
		m_pSqliteWrapper = new SQLiteWrapper();
		if (m_pSqliteWrapper == NULL)
		{
			return false;
		}
	}

	if (!m_pSqliteWrapper->Open(strDBPath))
	{
		// TODO: LOG_ERROR
		// m_pSqliteWrapper->LastError();
		ReleaseHandle();
		return false;
	}

	const std::string strSQL = "create table if not exists UPLOAD_EXE_INFO(MD5 text primary key not null, OriginalFilename text);";
	if (!m_pSqliteWrapper->DirectStatement(strSQL))
	{
		// TODO: LOG_ERROR
		// m_pSqliteWrapper->LastError();
		ReleaseHandle();
		return false;
	}

	return true;
}



void ExeUploadInfoDatabase::ReleaseHandle()
{
	if (m_pSqliteWrapper != NULL)
	{
		delete m_pSqliteWrapper;
		m_pSqliteWrapper = NULL;
	}
}


bool ExeUploadInfoDatabase::InsertData(InnerDbInfo& innerDb)
{
	bool bRet = false;
	const std::string strSQL = "insert into UPLOAD_EXE_INFO values(?, ?);";
	if (m_pSqliteWrapper != NULL)
	{
		SQLiteStatement *pStat = m_pSqliteWrapper->Statement(strSQL);
		if (pStat != NULL)
		{
			if (pStat->Bind(0, innerDb.strMD5))
			{
				if (pStat->Bind(1, innerDb.strOriginalFilename))
				{
					if (pStat->Execute())
					{
						bRet = true;
					}
				}
			}
		}

		if (pStat != NULL)
		{
			delete pStat;
			pStat = NULL;
		}
	}

	return bRet;
}


bool ExeUploadInfoDatabase::QueryData(std::string& strMD5, std::string& strOriginalFileName)
{
	bool bRet = false;
	const std::string strSQL = "select OriginalFilename from UPLOAD_EXE_INFO where MD5 = '" + strMD5 + "';";
	if (m_pSqliteWrapper != NULL)
	{
		SQLiteStatement *pStat = m_pSqliteWrapper->Statement(strSQL);
		if (pStat != NULL)
		{
			if (pStat->NextRow())
			{
				strOriginalFileName = pStat->ValueString(0);
				if (!strOriginalFileName.empty())
				{
					bRet = true;
				}
			}
		}

		if (pStat != NULL)
		{
			delete pStat;
			pStat = NULL;
		}
	}

	return bRet;
}
